<template>
  <div class="review-form">
    <el-form :model="formData" :rules="rules" ref="formRef">
      <!-- 评分 -->
      <el-form-item label="总体评分" prop="rating">
        <div class="rating-wrapper">
          <el-rate
            v-model="formData.rating"
            :texts="['很差', '较差', '一般', '不错', '很棒']"
            show-text
            allow-half
          />
        </div>
      </el-form-item>

      <!-- 标签选择 -->
      <el-form-item label="印象标签" prop="tags">
        <div class="tags-wrapper grid grid-cols-3 gap-2">
          <el-check-tag
            v-for="tag in availableTags"
            :key="tag.value"
            :checked="formData.tags.includes(tag.value)"
            @change="toggleTag(tag.value)"
          >
            {{ tag.label }}
          </el-check-tag>
        </div>
      </el-form-item>

      <!-- 评价内容 -->
      <el-form-item label="评价内容" prop="content">
        <el-input
          v-model="formData.content"
          type="textarea"
          :rows="4"
          placeholder="分享您的游玩体验，帮助其他游客更好地了解景点..."
          resize="none"
        />
      </el-form-item>

      <!-- 图片上传 -->
      <el-form-item label="上传图片">
        <el-upload
          v-model:file-list="formData.images"
          action="/api/upload"
          list-type="picture-card"
          :limit="9"
          :on-preview="handlePictureCardPreview"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <!-- 图片预览 -->
        <el-dialog v-model="previewVisible" width="800px">
          <img w-full :src="previewUrl" alt="Preview" />
        </el-dialog>
      </el-form-item>

      <!-- 是否匿名 -->
      <el-form-item>
        <el-checkbox v-model="formData.isAnonymous"> 匿名发布 </el-checkbox>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="actions flex justify-end space-x-3 mt-6">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">
        发布点评
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

const props = defineProps({
  spotId: {
    type: [String, Number],
    required: true,
  },
});

const emit = defineEmits(["submit", "cancel"]);

// 表单数据
const formData = reactive({
  rating: 5,
  tags: [],
  content: "",
  images: [],
  isAnonymous: false,
});

// 表单规则
const rules = {
  rating: [{ required: true, message: "请选择评分", trigger: "change" }],
  content: [
    { required: true, message: "请填写评价内容", trigger: "blur" },
    { min: 10, message: "评价内容至少10个字", trigger: "blur" },
  ],
};

// 可选标签
const availableTags = [
  { label: "环境优美", value: "environment" },
  { label: "服务周到", value: "service" },
  { label: "交通便利", value: "traffic" },
  { label: "设施完善", value: "facilities" },
  { label: "性价比高", value: "value" },
  { label: "特色鲜明", value: "special" },
  { label: "适合拍照", value: "photo" },
  { label: "人气旺盛", value: "popular" },
  { label: "清净优雅", value: "quiet" },
];

// 表单ref
const formRef = ref(null);

// 提交状态
const submitting = ref(false);

// 图片预览
const previewVisible = ref(false);
const previewUrl = ref("");

// 切换标签
const toggleTag = (tag) => {
  const index = formData.tags.indexOf(tag);
  if (index > -1) {
    formData.tags.splice(index, 1);
  } else {
    if (formData.tags.length < 3) {
      formData.tags.push(tag);
    } else {
      ElMessage.warning("最多选择3个标签");
    }
  }
};

// 处理图片预览
const handlePictureCardPreview = (file) => {
  previewUrl.value = file.url;
  previewVisible.value = true;
};

// 处理上传成功
const handleUploadSuccess = (response, file) => {
  file.url = response.url;
};

// 上传前检查
const beforeUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件！");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB！");
    return false;
  }
  return true;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitting.value = true;

    // 构建提交数据
    const submitData = {
      ...formData,
      spotId: props.spotId,
      images: formData.images.map((img) => img.url),
    };

    emit("submit", submitData);
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    submitting.value = false;
  }
};

// 取消
const handleCancel = () => {
  emit("cancel");
};
</script>

<style lang="scss" scoped>
.review-form {
  .rating-wrapper {
    @apply py-2;
  }

  .tags-wrapper {
    :deep(.el-check-tag) {
      @apply cursor-pointer text-center py-2;

      &.is-checked {
        @apply bg-primary-50 text-primary-600 border-primary-200;
      }
    }
  }

  :deep(.el-upload--picture-card) {
    @apply w-24 h-24;
  }
}
</style>
